<template>
  <div class="dashboard-container">
    <el-drawer ref="drawer" size="500px" title="D82订单补全" :visible.sync="showDialog" :wrapper-closable="true" @close="close">
      <div class="upload-draw">
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          accept=".xls,.xlsx"
          action="https://localhost:8080/posts/"
          :on-change="upload"
          :show-file-list="false"
          :auto-upload="false"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-button
          slot="trigger"
          icon="el-icon-download"
          type="primary"
          @click="downLoadModel"
        >D82补全模板下载</el-button>
      </div>
    </el-drawer>

    <el-dialog
      title="导入结果"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >

      <div style="padding:20px">
        <div style="margin-bottom:10px">
          共<span style="color:#000;font-size:16px"> {{ total }}</span> 条,导入成功 <span style="color:green;font-size:16px">{{ total-errorList.length }}</span>  条,失败 <span style="color:red;font-size:16px">{{ errorList.length }} </span> 条
        </div>
        <el-table
          v-if="errorList.length"
          :data="errorList"
          style="width: 100%"
          height="500px"
        >
          <el-table-column
            prop="line"
            label="行数"
            width="50"
          />
          <el-table-column
            prop="first_waybill_no"
            label="订单号"
            width="120"
          />
          <el-table-column
            prop="errMsg"
            label="错误原因"
          />
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import xlsx from 'xlsx'
import { sheet2Data } from '@/utils/excel'
import _ from 'lodash'
import { AddressCorrectNew, completionOrder, downTemplate } from '@/api/order/index'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // eslint-disable-next-line vue/require-prop-types
    listQuery: {
      default: false

    }
  },
  data() {
    return {
      showDialog: false,
      errorList: [],
      dialogVisible: false,
      total: 0
    }
  },
  watch: {
    visible(val) {
      this.showDialog = this.visible
    }
  },
  methods: {
    close() {
      this.$emit('update', false)
    },
    handleClose() {
      this.dialogVisible = false
    },
    downLoadModel() {
      downTemplate(this.listQuery).then(res => {
        this.downloadHandler(res)
      })
    },
    downloadHandler(data) {
      // 匹配任意文件类型：type : "application/octet-stream"
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      })
      // 获取heads中的filename文件名
      const downloadElement = document.createElement('a')
      // 创建下载的链接
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      // 下载后文件名
      downloadElement.download = 'D82订单补全.xlsx'
      document.body.appendChild(downloadElement)
      // 点击下载
      downloadElement.click()
      // 下载完成移除元素
      document.body.removeChild(downloadElement)
      // 释放掉blob对象
      window.URL.revokeObjectURL(href)
    },
    upload(file, fileList) {
      console.log(file)
      const files = { 0: file.raw }// 取到File
      this.readExcel(files)
    },
    addressCorrect(address) {
      return new Promise((resolve, reject) => {
        if (address) {
          AddressCorrectNew({
            country: 'CN',
            address: address
          }).then((res) => {
            resolve({
              province: res.data.state,
              city: res.data.city,
              district: res.data.district,
              detailed: res.data.detail
            })
          })
        } else {
          resolve({
            province: '',
            city: '',
            district: '',
            detailed: ''
          })
        }
      })
    },
    readExcel(files) { // 表格导入
      if (files.length <= 0) { // 如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }
      this.loadingExcel = this.$loading({
        lock: true,
        text: '导入数据中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const fileReader = new FileReader()
      fileReader.onload = async(files) => {
        try {
          const data = files.target.result
          const workbook = xlsx.read(data, {
            type: 'binary'
          })
          const worksheet = workbook.Sheets[workbook.SheetNames[0]]
          // data = XLSX.utils.sheet_to_json(worksheet);
          const file = sheet2Data(worksheet, 'AW')
          const arr = [
            '包裹号', '运单号', '包裹重量(KG)', '收件人姓名', '收件地址（需要填写正确省市区）', '收件人手机号码', '收件人邮编', '备注', '快递产品类型', '货物类型', '卫衣', '开衫', '毛衣/针织衫', '衬衫', 'T恤', '背心', '内衣', '连衣裙', '半身裙', '休闲裤', '短款', '牛仔裤', '羊绒大衣', '风衣', '西服', '羽绒服', '棉服', '夹克', '发夹', '发圈', '发箍', '项链', '手链/脚链', '耳环', '运动鞋', '皮鞋', '拖鞋', '凉鞋', '长靴', '双肩包', '皮包', '布包', '帽子', '袜子', '手套', '腰带', '丝巾', '围巾', '文件'
          ]
          console.log(file[4])
          console.log(arr)
          if (!_.isEqual(arr, file[4])) {
            this.$message.error('上传模版错误')
            this.loadingExcel.close()
            return false
          }
          // 重写数据
          const goodList = file.splice(5, file.length - 1)
          const arrList = []
          for (const index in goodList) {
            const detail = []
            const item = goodList[index]
            const address = await this.addressCorrect(item[4])
            for (let i = 0; i < item.length; i++) {
              if (i >= 10 && item[i]) {
                detail.push({
                  cate2: arr[i],
                  num: item[i]
                })
              }
            }
            const obj = {
              order_no: item[0],
              first_waybill_no: item[1],
              weight_report: item[2],
              receiver_info: {
                name: item[3],
                area_code: 86,
                mobile: item[5],
                postcode: item[6],
                nation: '中国',
                province: address.province,
                city: address.city,
                district: address.district,
                detailed: address.detailed
              },
              remarks: item[7],
              goods_type: item[9],
              express_type: item[8],
              detail: detail,
              line: Number(index) + 5
            }
            arrList.push(obj)
          }
          this.total = arrList.length
          const chunkList = _.chunk(arrList, 10)
          this.errorList = []
          for (let index = 0; index < chunkList.length; index++) {
            const element = chunkList[index]
            await this.completionOrderChunk(element)
          }
          this.$message.success('导入完成')
          this.dialogVisible = true
          this.loadingExcel.close()
          this.$emit('reload', false)
          this.$refs.upload.value = ''
          // return ws
        } catch (e) {
          console.log(e)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    completionOrderChunk(list) {
      return new Promise((resolve, reject) => {
        completionOrder({
          list: list
        }).then(res => {
          this.errorList = this.errorList.concat(res.data.errorList)
          resolve(res.msg)
        })
      })
    }
  }
}

</script>

<style lang="scss" scoped>
.upload-draw{
  padding: 50px;
}
</style>
